﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RKConsulting.Helpers
{
    public static class EnumHelper
    {
        // http://stackoverflow.com/questions/1424971/parse-string-to-enum-type
        public static T Parse<T>(string input) where T : struct
        {
            //since we cant do a generic type constraint
            if (!typeof(T).IsEnum)
                throw new ArgumentException("Generic Type 'T' must be an Enum");

            if (!string.IsNullOrEmpty(input))
            {
                int val;
                if (int.TryParse(input, out val))
                    return (T)(object)val;

                if (Enum.GetNames(typeof(T)).Any(
                      e => e.Trim().ToUpperInvariant() == input.Trim().ToUpperInvariant()))
                {
                    return (T)Enum.Parse(typeof(T), input, true);
                }
            }
            
            throw new InvalidCastException("input is not a valid " + typeof(T));
        }

        // http://stackoverflow.com/questions/61953/how-do-you-bind-an-enum-to-a-dropdownlist-control-in-asp-net
        public static IDictionary<int, string> GetAll<TEnum>() where TEnum : struct
        {
            var enumerationType = typeof(TEnum);

            if (!enumerationType.IsEnum)
                throw new ArgumentException("Enumeration type is expected.");

            var dictionary = new Dictionary<int, string>();

            foreach (int value in Enum.GetValues(enumerationType))
            {
                var name = Enum.GetName(enumerationType, value);
                dictionary.Add(value, name);
            }

            return dictionary;
        }

        public static string ToSpacesString<TEnum>(TEnum value) where TEnum : struct
        {
            if (!typeof(TEnum).IsEnum)
                throw new ArgumentException("Generic Type 'T' must be an Enum");

            return StringHelper.InsertSpacesToCamelCaseString(value.ToString());
        }
    }
}
